package simbot.example.service.push.info.animation.impl;

import catcode.CatCodeUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import love.forte.simbot.api.message.containers.GroupCodeContainer;
import love.forte.simbot.api.message.results.GroupList;
import love.forte.simbot.api.sender.BotSender;
import love.forte.simbot.api.sender.Getter;
import love.forte.simbot.api.sender.Sender;
import love.forte.simbot.bot.Bot;
import love.forte.simbot.core.SimbotContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import simbot.example.config.pool.ScheduleAnimationThreadPoolConfig;
import simbot.example.config.system.HttpProxyConfig;
import simbot.example.config.system.RoBotConfig;
import simbot.example.dto.BangumiDTO;
import simbot.example.options.animation.AnimationPushOptions;
import simbot.example.service.produce.info.animation.BangumiService;
import simbot.example.service.push.info.animation.IAnimationInfoPushService;
import simbot.example.utils.client.HttpClientUtil;

import javax.annotation.Resource;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 每日动画发送表推送
 * 该类使用默认的Bot进行发送
 *
 * @author minmin
 * @since 2021/07/02 22:08
 */
@Service
@Slf4j
@Setter
public class DailyAnimationTablePushServiceImpl implements IAnimationInfoPushService {
    @Resource
    private BangumiService bangumiService;

    @Resource
    private SimbotContext simbotContext;

    @Resource
    private ScheduleAnimationThreadPoolConfig scheduleAnimationThreadPoolConfig;

    @Resource
    private HttpProxyConfig httpProxyConfig;

    @Resource
    private RoBotConfig roBotConfig;

    private CountDownLatch countDownLatch;

    @Override
    public void pushInfo() {
        List<String> groupList = getGroupList();
        log.debug("DailyAnimationTablePushServiceImpl.pushInfo groupList:{}", groupList);
        BotSender botSender = getBot().getSender();
        Sender sender = botSender.SENDER;
        for (String group : groupList) {
            try {
                BangumiDTO bangumiDTO = bangumiService.getAnimationCalendarByDaily();
                countDownLatch = new CountDownLatch(bangumiDTO.getItems().size());
                downloadToLocal(bangumiDTO);
                if (!countDownLatch.await(30, TimeUnit.SECONDS)) {
                    throw new RuntimeException("每日推送等待downloadToLocal方法超时");
                }
                sender.sendGroupMsg(group, bangumiDTO.toString());
            } catch (Exception e) {
                // 发生错误 比如配置的群号bot不存在群中 后续添加Aop捕获异常处理
                e.printStackTrace();
                log.error("推送每日动画信息出错 error:{} BotQQ:{}, GroupId:{}", e.getMessage(), botSender.getBotInfo().getAccountCode(), group);
            }
        }
    }

    @Value("${animation.push.mode}")
    private String mode;

    private List<String> getGroupList(){
        try {
            switch (AnimationPushOptions.valueOf(mode)){
                case SCOPE:
                    return scheduleAnimationThreadPoolConfig.getGroups();
                case ALL:
                    BotSender botSender = getBot().getSender();
                    Getter getter = botSender.GETTER;
                    GroupList groupList = getter.getGroupList();
                    return groupList.stream().map(GroupCodeContainer::getGroupCode).collect(Collectors.toList());
                default:
                    throw new RuntimeException("animation.push.mode 参数设置异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("animation.push.mode 参数设置异常 mode值:{}", mode);
            return Collections.emptyList();
        }
    }

    private void downloadToLocal(BangumiDTO bangumiDTO) {
        for (BangumiDTO.Item item : bangumiDTO.getItems()) {
            try {
                String imageUrl = item.getImage();
                String imageFileName = getImageName(imageUrl);
                String localPath = Paths.get(roBotConfig.getImageDir(), imageFileName).toString();
                if (checkLocalImage(localPath)) {
                    localPath = HttpClientUtil.doGetDownloadFile(roBotConfig.getImageDir(), imageFileName, imageUrl, null, httpProxyConfig.getHttpProxyHost());
                }
                item.setImage(CatCodeUtil.getInstance().getStringCodeBuilder("image", true).key("file").value(localPath).build());
            } catch (Exception e) {
                e.printStackTrace();
                log.debug("下载文件出错:{}", e.getMessage());
            } finally {
                countDownLatch.countDown();
            }
        }
    }

    private boolean checkLocalImage(String path) {
        return Files.notExists(Paths.get(path));
    }

    private String getImageName(String imageUrl) {
        return imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
    }

    private Bot getBot() {
        return simbotContext.getBotManager().getDefaultBot();
    }
}
